package com.yingli.camera_system.gallery;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.yingli.camera_system.R;

import java.util.ArrayList;
import java.util.Collections;

public class Gallery_Activity extends AppCompatActivity {

    private Button btnGallery;

    //选择完相册里的相片后回显的ImageView
    private ImageView ivPreview;

    private ArrayList<String> allPaths;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        btnGallery = findViewById(R.id.btn_gallery);
        ivPreview = findViewById(R.id.iv_preview);

        btnGallery.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent,2);
        });
        initAlbum();
    }
    public void initAlbum() {
        allPaths = new ArrayList<>();
        allPaths = getGallery(getContentResolver());
        Log.i("albums",allPaths.toString());
        Glide.with(this).load(allPaths.get(0)).into(ivPreview);
    }
    //获取系统相册里面的所有相片
    private ArrayList<String> getGallery (ContentResolver contentResolver){
        ArrayList<String> galleryList = new ArrayList<>();
        final String [] columns = {MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID};
        final String orderBy = MediaStore.Images.Media._ID;
        //查询游标
        Cursor imageCursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,columns,null,null,orderBy);
        if (imageCursor!=null && imageCursor.getCount()>0){
            while (imageCursor.moveToNext()){
                int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
                String path = "file://"+imageCursor.getString(dataColumnIndex);
                Log.d("tgw5", "getGalleryPhotos: " + path);
                galleryList.add(path);
            }
        }
        Collections.reverse(galleryList);
        return galleryList;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 2:
                if (data!=null){
                    //大与等于SDK19的版本需要特殊处理
                    if (Build.VERSION.SDK_INT>=19)
                        handImage(data);
                    else
                        handImageLow(data);
                }
                break;
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handImage(Intent data){
        String path =null;
        //获取相片的Uri
        Uri uri = data.getData();
        //根据不同的uri进行不同的解析
        if (DocumentsContract.isDocumentUri(this,uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            //如果有获取系统媒体文件的权限
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                path = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            path = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            path = uri.getPath();
        }
        //展示图片
        displayImage(path);
    }


    //安卓小于4.4的处理方法
    private void handImageLow(Intent data){
        Uri uri = data.getData();
        String path = getImagePath(uri,null);
        displayImage(path);
    }

    //content类型的uri获取图片路径的方法
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor!=null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //根据路径展示图片的方法
    private void displayImage(String imagePath){
        if (imagePath != null){
            //通过本地的文件来初始化Bitmap对象
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ivPreview.setImageBitmap(bitmap);
        }else{
            Toast.makeText(this,"fail to set image",Toast.LENGTH_SHORT).show();
        }
    }

}
